<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\Task;
use DB;
use Validator;
use Carbon\Carbon;
use App\Models\DeviceGroupTask;
use App\Models\DeviceGroup;
use Illuminate\Http\Request;

class deviceGroupTaskController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'device_group_id' => 'required|exists:device_groups,id',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $device_group_tasks = DeviceGroupTask::with('task')
      ->where('device_group_id', $request->device_group_id)
      ->orderBy('priority', 'desc')
      ->get();
    return $this->success(0, '', $device_group_tasks);
  }

  public function getOne(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'device_id' => 'required|exists:devices,id',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $device = Device::findOrFail($request->device_id);
    $device_group = DeviceGroup::findOrFail($device->device_group_id);
    $time_condition = Carbon::now()->toDateTimeString();

      $query = DeviceGroupTask::where('device_group_id', $device->device_group_id);
      // 当 task_is_circle 为 true 时，忽略年月日时间的筛选条件
      if($device_group->task_is_circle) {
          $query->where(DB::raw("DATE_FORMAT(publish_start_time,'%H-%i-%s')"),'<=', date('H-i-s'))
              ->where(DB::raw("DATE_FORMAT(publish_end_time,'%H-%i-%s')"),'>=', date('H-i-s'));
      } else {
          $query->where('publish_start_time', '<=', $time_condition)->where('publish_end_time', '>=', $time_condition);
      }
      $query = $query->orderBy('priority','desc')->limit(999);//先排序，后分组
      $device_group_tasks = DB::table(DB::raw("({$query->toSql()}) b"))
          ->mergeBindings($query->getQuery())
          ->orderBy('priority','desc')
          ->groupBy('task_id')//分组后再排序
          ->get();

      $task = null;
      foreach ($device_group_tasks as $row){//判断cd
          $last_finished_time = DeviceGroupTask::where('task_id', $row->task_id)
              ->where('device_group_id', $device->device_group_id)
              ->leftJoin(DB::raw('(SELECT device_group_task_id,max(finished_time) finished_time FROM `task_device` WHERE device_id='.$request->device_id.' GROUP BY device_group_task_id) t'),function ($join){$join->on('device_group_tasks.id','=','t.device_group_task_id');})
              ->max('finished_time');
          $row->task = Task::where('id',$row->task_id)->first(['id','name','status','cd']);
          if(time() < strtotime($last_finished_time)+$row->task->cd)
              continue;//CD还没好,找下一个任务
          $task = json_decode(json_encode($row),true);
          break;
      }

    $this->deviceDetailedList($type=1,$detail_type=4,$request->device_id);
    return $this->success(0, '', $task);
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'device_group_id' => 'required|exists:device_groups,id',
      'task_id' => 'required|exists:tasks,id',
      'priority' => 'required|numeric|max:100,min:0',
      'publish_start_time' => 'required|date_format:Y-m-d H:i:s',
      'publish_end_time' => 'required|date_format:Y-m-d H:i:s',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $cred = $request->only('device_group_id', 'task_id', 'priority', 'publish_start_time', 'publish_end_time');
    $device_group_task = DeviceGroupTask::create($cred);
    return $this->success(0, '', $device_group_task);
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @param  int $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    $validator = Validator::make($request->all(), [
      'device_group_id' => 'sometimes|required|exists:device_groups,id',
      'task_id' => 'sometimes|required|exists:tasks,id',
      'priority' => 'sometimes|required|numeric|max:100,min:0',
      'publish_start_time' => 'sometimes|required|date_format:Y-m-d H:i:s',
      'publish_end_time' => 'sometimes|required|date_format:Y-m-d H:i:s',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $device_group_task = DeviceGroupTask::findOrFail($id);
    $cred = $request->only('device_group_id', 'task_id', 'priority', 'publish_start_time', 'publish_end_time');
    $device_group_task->update($cred);
    return $this->success(0, '', $device_group_task);
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    DeviceGroupTask::destroy($id);
    return $this->success(0, '删除成功');
  }

  public function finishedDevice(Request $request, $id)
  {
      $validator = Validator::make($request->all(), [
          'device_id' => 'required|exists:devices,id',
          'sns_id' => 'sometimes|required|exists:sns,id'
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      $device_group_task = DeviceGroupTask::findOrFail($id);
      $device_group_task->addFinishedDevices($request->device_id);
      $this->deviceDetailedList($type=2,$detail_type=4,$request->device_id);//总完成任务次数统计

      $return = null;
      switch ($device_group_task->task_id){
          case 1:  return $this->success(0, '');//加粉已单独作另一个数据，此计数接口闲置
          case 2: $detail_type = 1;//发朋友圈
              if(!$request->sns_id) break;//无sns_id直接记录次数
              SnsController::postedDevice($request);
              break;
          case 3: $detail_type = 2; break;//查支付宝(fans)
          case 4: $detail_type = 8; break;//检测微信(data resources)
          case 5: $detail_type = 3; break;//设备行为模拟操作
          default: return $this->failure(-1, 'task_id error');
      }
      $count = $this->deviceDetailedList($type=2,$detail_type,$request->device_id);//个别任务数量统计
      return $this->success(0, '操作成功', $count);
  }

  public function deleteAll(Request $request)
  {
    DeviceGroupTask::where('device_group_id', $request->device_group_id)->delete();
    return $this->success(0, '');
  }

  public function reset($id)
  {
    $device_group_task = DeviceGroupTask::findOrFail($id);
    DB::table('task_device')->where('device_group_task_id', $device_group_task->id)->delete();
    return $this->success(0, '', null);
  }
}
